#include "tklog.h"
#include "tkerror.h"
#include "proto.h"
#include "commproto.h"
#include "constants.h"

void init_member_list(memberlist *mlist, int cmd_type) 
{
	memset(mlist, 0x00, sizeof(memberlist));
	mlist->cmd = cmd_type;
	mlist->_clientinfo_size = sizeof(mlist->clientinfo) / sizeof(mlist->clientinfo[0]);
	mlist->_clientinfo_count = 0;
}

int add_member(memberlist *mlist, member *m)
{
	if (mlist->_clientinfo_size == mlist->_clientinfo_count)	
		return TK_TOOMUCH_MEMBER;
	
	int i = mlist->_clientinfo_count;

	mlist->clientinfo[i].clientid = m->clientid;
	strcpy(mlist->clientinfo[i].clientname, m->clientname);
	strcpy(mlist->clientinfo[i].ip, m->ip);

	mlist->_clientinfo_count++;

	return 0;
}

int query_member_byname(memberlist *mlist, member *m)
{
	int i;

	for (i = 0; i < mlist->_clientinfo_count; i++) {
		if (strcmp(mlist->clientinfo[i].clientname, m->clientname) == 0) {
			m->clientid = mlist->clientinfo[i].clientid;
			strcpy(m->clientname, mlist->clientinfo[i].clientname);
			strcpy(m->ip, mlist->clientinfo[i].ip);

			return TK_NOT_FOUND;
		}
	}

	return 0;
}

int query_member_byid(memberlist *mlist, member *m)
{
        int i;

        for (i = 0; i < mlist->_clientinfo_count; i++) {
                if (mlist->clientinfo[i].clientid == m->clientid) {
                        strcpy(m->clientname, mlist->clientinfo[i].clientname);
                        strcpy(m->ip, mlist->clientinfo[i].ip);
			
			return 0;
                }
        }               
        
	return TK_NOT_FOUND;
}

int query_member_byip(memberlist *mlist, member *m)
{
        int i;

        for (i = 0; i < mlist->_clientinfo_count; i++) {
                if (strcmp(mlist->clientinfo[i].ip, m->ip) == 0) {
			m->clientid = mlist->clientinfo[i].clientid;
                        strcpy(m->clientname, mlist->clientinfo[i].clientname);

                        return 0;
                }
        }

	return TK_NOT_FOUND;
}

/* at most del one member */
int del_member(memberlist *mlist, int clientid)
{
	int i;
	int found = 0;

        for (i = 0; i < mlist->_clientinfo_count; i++) {
                if (found == 0 && mlist->clientinfo[i].clientid == clientid) {
			found = 1;
		}
		else if (found == 1) {
			memcpy(&mlist->clientinfo[i - 1], &mlist->clientinfo[i], sizeof(mlist->clientinfo[i]));
		}
        }

	if (found == 1) {
		mlist->_clientinfo_count--;
		return 0;
	}
	else {
		return TK_NOT_FOUND;
	}
}
